const { default: axios } = require("axios")
const userModel = require("../model/user")
const md5 = require("crypto-js/md5")
class User {
    /**
     * 注册接口
     * @param {*} ctx 
     * @param {username} 用户名
     * @param {password} 密码
     * @param {email} 邮箱
     * @param {mobile} 手机号
     * @param {headpic} 头像
     */
    static async createUser(ctx) {
        // /ctx.request.body 接收 post 值  ctx.query 接收get的参数值
        let { username, password, email, mobile, headpic } = ctx.request.body
        if (!username || !password) {
            ctx.body = {
                code: 202,
                codeInfo: "参数不足"
            }
        } else {
            //先查询改用户 是否已经注册 
            let user = await userModel.getUser(username)
            if (user.length > 0) {
                //不允许重复注册
                ctx.body = {
                    code: 201,
                    codeInfo: "不允许重复注册"
                }
            } else {

                let users = { ip: '', username, password, email, mobile, headpic }
                //将密码用md5进行加密 
                users.password = md5(users.password).toString()
                console.log(user, 35)
                let res = await userModel.addUser(users)
                ctx.body = {
                    code: 200,
                    codeInfo: "注册成功",
                    res: res
                }
            }
        }

    }

    static async doLogin(ctx) {
        let { username, password } = ctx.request.body
        //1 查询用户是否存在
        let user = await userModel.getUser(username)
        if (user.length > 0) {
            //说明用户存在
            //判断密码是否正确
            if (user[0].password === md5(password).toString()) {
                //1 生成token 并且给token设置一个过期时间
                let token = ctx.jwt.get({ ...user[0] })
                ctx.body = {
                    code: 200,
                    codeInfo: "成功",
                    token: token
                }
            } else {
                ctx.body = {
                    code: 202,
                    codeInfo: "密码错误"
                }
            }
        } else {
            //说明用户不存在
            ctx.body = {
                code: 201,
                codeInfo: "用户不存在"
            }
        }
    }


    //微信授权登录 根据code换取access_token
    static async getAccessToken(ctx) {
        let { code,avatarUrl,nickName } = ctx.request.body
        var config = {
            method: 'get',
            url: `https://api.weixin.qq.com/sns/jscode2session?appid=${ctx.env.WEIXIN_APPID}&secret=${ctx.env.WEIXIN_SCRECT}&js_code=${code}&grant_type=authorization_code`,
            headers: {}
        };
        //调用 微信公众平台 接口 同步获取 opennid
        let user = await axios(config)
        //将openid 从 接口返回数据中 解构出来
        let { openid } = user.data
        console.log(user,91)
        //第一步 是为了 检查 用户是否已经注册 
        let users = await userModel.getUserOpenId(openid)
        console.log(users,94)
        //第三步 如果已经注册 登录成功 返回用户信息
        if (users.length > 0) {
            //1 生成token 并且给token设置一个过期时间
            let token = ctx.jwt.get({ ...users[0] })
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                token: token
            }
        } else {
            // 第二步 用户 没有注册 需要自动注册 并且将用户存储到 数据表中
            //先注册 
            let obj = { nickname: nickName ,headpic:avatarUrl, openid: openid }
            //将用户添加到数据库里面
            await userModel.addUser(obj)
            //在查询一下用户 获取下用户信息 
            users = await userModel.getUserOpenId(openid)
            //生成token 进行成功返回
            let token = ctx.jwt.get({ ...users[0] })
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                token: token
            }
        }
    }

    static async getUserInfo(ctx) {
        //ctx token 通过token将用户id拿出来 
        let { id } = User.checkToken(ctx)
        let users = await userModel.userInfo(id)//[{id.....}]
        ctx.body = {
            code: 200,
            codeInfo: "成功",
            data: users[0]
        }
    }

    static async saveHeadpic(ctx) {
        let { headpic, id } = ctx.request.body
        let res = await userModel.saveUser("headpic", headpic, id)
        ctx.body = {
            code: 200,
            codeInfo: "成功",
            res: res
        }
    }

    static async saveNickname(ctx) {
        let { nickname, id } = ctx.request.body
        let res = await userModel.saveUser("nickname", nickname, id)
        ctx.body = {
            code: 200,
            codeInfo: "成功",
            res: res
        }
    }

    //xhr.status:获取当前服务器的响应状态  200=>成功
    static async saveMobile(ctx) {
        let { mobile, id } = ctx.request.body
        let res = await userModel.saveUser("mobile", mobile, id)
        if (res) {
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                res: res
            }
        } else {
            ctx.body = {
                code: 201,
                codeInfo: "保存失败，请检查保存信息是否已经被注册了",
            }
        }
    }

    static async saveEmail(ctx) {
        let { email, id } = ctx.request.body
        let res = await userModel.saveUser("email", email, id)
        if (res) {
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                res: res
            }
        } else {
            ctx.body = {
                code: 201,
                codeInfo: "保存失败，请检查保存信息是否已经被注册了",
            }
        }

    }

    static async saveUsername(ctx) {
        let { username, id } = ctx.request.body
        let res = await userModel.saveUser("username", username, id)
        if (res) {
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                res: res
            }
        } else {
            ctx.body = {
                code: 201,
                codeInfo: "保存失败，请检查保存信息是否已经被注册了",
            }
        }
    }

    static async saveOpenid(ctx) {
        let { openid, id } = ctx.request.body
        let res = await userModel.saveUser("openid", openid, id)
        if (res) {
            ctx.body = {
                code: 200,
                codeInfo: "成功",
                res: res
            }
        } else {
            ctx.body = {
                code: 201,
                codeInfo: "保存失败，请检查保存信息是否已经被注册了",
            }
        }
    }


    static checkToken(ctx) {
        return ctx.jwt.check(ctx.header.authorization)
    }


    static async kfDoLogin(ctx) {
        let { username, password } = ctx.request.body
        let res = await userModel.getKfUser(username)
        if (res.length > 0) {
            password = md5(password).toString()
            if (res[0].password == password) {
                let token = ctx.jwt.get({ ...res[0] }, 2 * 60 * 60)
                ctx.body = {
                    code: 200,
                    codeInfo: "成功",
                    token: token,
                    userinfo: res[0]
                }
            } else {
                ctx.body = {
                    code: 201,
                    codeInfo: "密码错误"
                }
            }
        } else {
            ctx.body = {
                code: 202,
                codeInfo: "用户不存在"
            }
        }
    }
    /**
     * 获取临时key的方法
     * @param {*} ctx 
     */
    static async getTempKey(ctx) {
        let now = new Date().getTime()
        let sjs = ctx.rand(10)
        let key = ctx.md5(now + "_" + sjs)
        ctx.body = {
            code: 200,
            codeInfo: "成功",
            temp_key: key
        }
    }

    /**
     * 刷新token
     * @param username  用户名
     * @param openid 微信openid
     * @param uid 用户id （必填）
     */
    static async refishToken(ctx) {
        let { uid, username,openid } = ctx.query
        let res
        if(openid){
            res = await userModel.getUserOpenId(openid)
        }else{
            res = await userModel.getUser(username)
        }
        if (res.length > 0) {
            if (res[0].id == uid) {
                ctx.body = {
                    code: 200,
                    codeInfo: "成功",
                    token: ctx.jwt.get({ ...res[0] }, 2 * 60 * 60)
                }
            } else {
                ctx.body = {
                    code: 201,
                    codeInfo: "参数有误"
                }
            }
        } else {
            ctx.body = {
                code: 202,
                codeInfo: "用户不存在"
            }
        }

    }
}
module.exports = User